<!-- 商品详情页面 -->
<template>
  <div class="shell">
    <!-- <h1>商品详情</h1> -->

    <!-- 操作按钮区域 -->
    <div id="top">
      <b>{{ goodinfo.product_name }}</b>
      <div class="actions">
        <el-button type="primary" @click="handleChat">AI咨询</el-button>
        <el-button type="primary" @click="handleContact">联系发布人</el-button>
        <el-button @click="handleBack">返回列表</el-button>
      </div>
    </div>


    <div class="product-detail-container">
      <!-- 左侧图片区域 -->
      <section class="left-section">
        <div id="show-image-div" @mouseenter="pauseCarousel" @mouseleave="resumeCarousel">
          <transition name="fade">
            <img v-if="showImage" :src="currentImage" alt="商品图">
          </transition>
        </div>

        <div class="thumbnail-container">
          <div v-for="(image, index) in goodinfo.images.slice(1, 5)" :key="index" class="thumbnail-item"
            @mouseover="changeImage(image)" @mouseenter="pauseCarousel" @mouseleave="resumeCarousel">
            <img :src="image" :alt="'缩略图' + (index + 1)">
          </div>
        </div>
      </section>
      <!-- 右侧信息区域 -->
      <section class="right-section">
        <div id="cover-img-div">
          <img id="cover-img" :src="goodinfo.images[0]" alt="封面图">
        </div>
        <ul class="meta-list">

          <li class="meta-item">
            <label>出售方：</label>
            <span>{{ goodinfo.seller.user_name }}</span>
          </li>
          <li class="meta-item">
            <label>分类： </label>
            <span id="type">{{ goodinfo.category }}</span>
          </li>
          <li class="meta-item">
            <label>单价：</label>
            <span id="price">￥{{ goodinfo.price }}/斤</span>
          </li>
          <li class="meta-item">
            <label>地区：</label>
            <span>{{ goodinfo.region }}</span>
          </li>
          <li class="meta-item">
            <label>当前库存/总量：</label>
            <span>{{ `${goodinfo.listed_quantity} 斤 / ${goodinfo.total_stock} 斤` }}</span>
          </li>
          <li class="meta-item">
            <label>上架时间：</label>
            <span>{{ goodinfo.created_at }}</span>
          </li>
          <li>
            <label>产品简介：</label>
          </li>
          <li class="product-intro">
            <p :title="goodinfo.description">{{ goodinfo.description }}</p>
          </li>

          <li>
              <label>购买数量<span style="font-size:13px;">(单位/斤)</span>：</label>
          </li>
          <li v-if="store.userdata.role_name === 'dealer'">
            <div class="purchase-section">
              <el-input-number v-model="farmerQuantity" :min="1" :step="1"
                controls-position="right" placeholder="请输入数量" />
              <el-button id="buyButton" type="primary" @click="handlePurchase"
                :disabled="!farmerQuantity">购买</el-button>
            </div>
          </li>
          <li v-if="store.userdata.role_name === 'farmer'">
            <div class="purchase-section prev">
              此平台用于帮助农户和经销商进行农产品对接，农户不能进行购买，仅可发布出售或去收购页出售
            </div>
          </li>
          <li v-if="store.userdata.role_name === 'gov'">
            <div class="purchase-section prev">
              此平台用于帮助农户和经销商进行农产品对接，政府用户不能直接进行购买，需在“政府收售”页发布收购公告
            </div>
          </li>

        </ul>
      </section>
    </div>

    <!-- 详细介绍 -->
    <div>
      <h1>产品详细介绍</h1>
      <div class="des-content">
        <div v-html="goodinfo.introduction ? marked.parse(goodinfo.introduction) : ''"></div>
      </div>
    </div>

    <!-- 确认购买弹窗 -->
    <el-dialog v-model="showBuyDialog" title="购买订单" width="550px" center>
      <div class="buy-dialog">
        <div class="order-item">
          <el-icon><User /></el-icon>
          <div class="order-content">
            <span class="label">购买人：</span>
            <span class="value">{{ store.userdata.nick_name }}</span>
          </div>
        </div>
        <div class="order-item">
          <el-icon><ShoppingCart /></el-icon>
          <div class="order-content">
            <span class="label">购买产品：</span>
            <span class="value">{{ goodinfo.product_name }}</span>
          </div>
        </div>
        <div class="order-item">
          <el-icon><Goods /></el-icon>
          <div class="order-content">
            <span class="label">购买数量：</span>
            <span class="value">{{ farmerQuantity }}斤</span>
          </div>
        </div>
        <div class="order-item">
          <el-icon><Money /></el-icon>
          <div class="order-content">
            <span class="label">单价：</span>
            <span class="value price">￥{{ goodinfo.price }}/斤</span>
          </div>
        </div>
        <div class="order-item">
          <el-icon><Wallet /></el-icon>
          <div class="order-content">
            <span class="label">总金额：</span>
            <span class="value total-price">￥{{ farmerQuantity * goodinfo.price }}元</span>
          </div>
        </div>
        <div class="order-item">
          <div class="order-content remark-section">
            <span class="label"><el-icon><ChatDotRound /></el-icon>备注：</span>
            <el-input v-model="buyerRemark" type="textarea" :rows="3" placeholder="请输入备注" />
          </div>
        </div>
      </div>
      <template #footer>
        <el-button type="primary" @click="confirmPurchase">确认支付</el-button>
        <el-button @click="showBuyDialog = false">取消</el-button>
      </template>
    </el-dialog>

    <!-- 联系方式弹窗 -->
    <el-dialog v-model="showContactDialog" title="联系方式" width="400px" center>
      <div class="contact-dialog">
        <div class="contact-item">
          <el-icon><User /></el-icon>
          <div class="contact-content">
            <span class="label">联系人：</span>
            <span class="value">{{ goodinfo.seller.user_name }}</span>
          </div>
        </div>
        <div class="contact-item">
          <el-icon><Phone /></el-icon>
          <div class="contact-content">
            <span class="label">联系电话：</span>
            <span class="value">{{ goodinfo.seller.phone }}</span>
          </div>
        </div>
        <div class="contact-item">
          <el-icon><Message /></el-icon>
          <div class="contact-content">
            <span class="label">电子邮箱：</span>
            <span class="value">{{ goodinfo.seller.email }}</span>
          </div>
        </div>
      </div>
      <template #footer>
        <el-button type="primary" @click="showContactDialog = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
// 商品详情页面组件
import { onMounted, ref, inject, onUnmounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useMainStore } from '@/stores';
import { User, Phone, Message, ShoppingCart, Goods, Money, Wallet, ChatDotRound } from '@element-plus/icons-vue';
import { marked } from 'marked';
const store = useMainStore();
const $tools = inject('$tools')
const $axios = inject('$axios')

const $route = useRoute();

const showContactDialog = ref(false);

const showBuyDialog = ref(false);


const currentImage = ref('');
// 切换大图路径
const showImage = ref(true);

const changeImage = (image) => {
  showImage.value = false;
  setTimeout(() => {
    currentImage.value = image;
    showImage.value = true;
  }, 500);
}
// 定时器 ID
let intervalId = null;

// 轮播是否暂停
const isCarouselPaused = ref(false);
// 启动轮播
const startCarousel = () => {
  let currentIndex = 1; // 从第二张图片开始（索引为1）
  intervalId = setInterval(() => {
    if (!isCarouselPaused.value) {
      showImage.value = false; // 先隐藏当前图片
      setTimeout(() => {
        currentIndex = (currentIndex + 1) % goodinfo.value.images.slice(1, 5).length;
        currentImage.value = goodinfo.value.images.slice(1, 5)[currentIndex];
        showImage.value = true; // 再显示新图片
      }, 500);
    }
  }, 4000); // 轮播间隔时间
};
// 暂停轮播
const pauseCarousel = () => {
  isCarouselPaused.value = true;
};// 恢复轮播
const resumeCarousel = () => {
  isCarouselPaused.value = false;
};
// 组件挂载时启动轮播
onMounted(() => {
  startCarousel();
});

// 组件卸载时清理定时器
onUnmounted(() => {
  if (intervalId) {
    clearInterval(intervalId);
  }
});

const goodinfo = ref({
  product_id: '',
  product_name: '',
  category: '',
  region: '',
  price: '',
  total_stock: '',
  listed_quantity: 1,
  status: '',
  description: '',
  introduction: '',
  created_at: '',
  seller: {
    email: '',
    phone: '',
    role: '',
    user_id: '',
    user_name: '',
  },
  images: []
})

onMounted(async () => {
  window.scrollTo({
    top: 0,
  })
  getGoodinfo();
  
});

async function getGoodinfo() {
  const id = $route.params.id; // 获取商品 ID
  // console.log(id);
  try {
    // 调用后端接口
    const response = await $axios.get('/agri_products/id', {

      params: {
        product_id: id
      }
    })
    // console.log(response.data);
    // console.log(store.userdata.nick_name);
    // console.log("id"+store.userdata.user_id);

    // 检查响应是否成功
    if (response.data.code === 200) {
      // 将接口返回的数据赋值给 goodinfo
      goodinfo.value = response.data.data;
      // 同步一下导航栏状态
      if(goodinfo.value.seller.role=="farmer") store.changeView(1);
      else store.changeView(2)
      console.log(response.data.data)
      goodinfo.value.created_at = new Date(goodinfo.value.created_at).toLocaleString();

      // console.log(goodinfo.value);

      // 设置当前显示的大图是第二张图片
      currentImage.value = goodinfo.value.images[1];
    }
  } catch (error) {
    console.error('获取商品详情失败：', error);
    $tools.alertMsg('获取商品详情失败，请稍后重试', 'error');
  }
}

// 处理联系按钮点击
const handleContact = () => {
  showContactDialog.value = true
}
const $router = useRouter();
// 处理返回按钮点击
const handleBack = () => {
  $router.back();
}
// 处理发起聊天
const handleChat = () => {
  // 设置导航栏状态为咨询室(索引3)
  sessionStorage.setItem('navView', 3)
  $router.push('/home/chat')
  showContactDialog.value = false
}

// 购买数量
const farmerQuantity = ref(null);
const buyerRemark = ref('');
const handlePurchase = () => {
  // 检查用户身份是否为经销商
  // if (store.userdata.role_name === "farmer") {
  //   $tools.alertMsg('此平台用于帮助农户和经销商进行农产品对接，农户不能进行购买，仅可发布出售或去收购页出售', 'error',4000)
  //   return;
  // }
  // if (store.userdata.role_name === "gov") {
  //   $tools.alertMsg('此平台用于帮助农户和经销商进行农产品对接，政府用户不能直接进行购买，需在“政府收售”页发布收购公告', 'error',4000)
  //   return;
  // }

  // 检查购买数量是否超过库存
  if (farmerQuantity.value > goodinfo.value.listed_quantity) {
    $tools.alertMsg(`购买数量不能超过当前库存(${goodinfo.value.listed_quantity}斤)，已调整为最大购买量`, 'error')
    farmerQuantity.value = goodinfo.value.listed_quantity
    return
  }
  showBuyDialog.value = true;
}

const confirmPurchase = async () => {
  showBuyDialog.value = false;

  // console.log(buyerRemark.value);

  await $axios.post('/orders/purchase', {
    seller_id: goodinfo.value.seller.user_id,
    items: [{
      product_id: goodinfo.value.product_id,
      quantity: farmerQuantity.value,
      product_type: "purchase",
      remarks: buyerRemark.value
    }
    ]
  })
  $tools.alertMsg(`成功购买${farmerQuantity.value}斤`, 'success')
  getGoodinfo();
  farmerQuantity.value = null
}
</script>

<style lang="less" scoped>
.shell {
  padding: 20px;
  color: #000;
  width: 1160px;
  background-color: white;
  margin-top: 5px;

  h1 {
    font-size: 24px;
    margin-bottom: 20px;
    color: #319A19;
  }
}

#top {
  width: 1120px;
  // border: 1px solid #ccc;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.3);
  border-radius: 5px;
  height: 60px;
  margin-bottom: 10px;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  padding-right: 15px;
  background-color: white;

  b {
    margin-left: 25px;
    font-size: 25px;
  }
}

.product-detail-container {
  display: flex;
  height: 680px;
  margin-bottom: 20px;
  background-color: rgb(250, 250, 250);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.2);
  // border: 1px solid #ccc;
  border-radius: 4px;
  padding: 20px;
}

.left-section {
  width: 700px;
  height: 620px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.15);
  border-radius: 5px;

  #show-image-div {
    width: 700px;
    height: 460px;
    // border-bottom: 1px solid #ccc;
    // border-radius: 5px;
    display: flex;
    justify-content: center;
    align-items: center;

    img {
      width: 98%;
      height: 98%;
      object-fit: contain;
      object-position: center;

    }
  }

  .thumbnail-container {
    display: flex;
    justify-content: space-between;
    height: 150px;
    width: 700px;
    // margin-top: 20px;
    padding: 10px;

    border-radius: 5px;

    .thumbnail-item {
      width: 24%;
      // border: 1px solid #ccc;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

      &:hover {
        cursor: pointer;
        background-color: rgb(210, 210, 210);
      }
    }

    .thumbnail-item img {
      width: 100%;
      height: 100%;
      object-fit: contain;
      object-position: center;
    }
  }
}

.right-section {
  width: 370px;
  height: 650px;
  padding-left: 20px;

  #cover-img-div {
    margin-top: 5px;
    width: 100%;
    height: 220px;
    margin-bottom: 15px;


    #cover-img {
      width: 100%;
      height: 100%;
      object-fit: contain;
      object-position: center;
    }
  }
}

.meta-list {
  list-style: none;
  margin: 0;
  padding: 20px 10px 15px 25px;
  height: 420px;

  li {
    margin-bottom: 3px;
    // padding-left: 5px;
    height: 30px;

    label {
      width: 80px;
      font-size: 16px;
      color: #909399;
      margin-right: 15px;
    }

    span {
      width: 200px;
      font-size: 17px;
    }




    #type {
      padding: 4px 8px;
      border-radius: 4px;
      font-size: 16px;
      background: #e8f5e9;
      color: #319A19;
    }

    #price {
      color: red;
    }


  }
}

.purchase-section {
  // height: 50px;
  display: flex;
  justify-content: center;
  flex-direction: row;
  align-items: center;
  padding-left:20px;
  #buyButton{
    margin-left: 14px;
  }
}
.prev{
  font-size: 14px;
  color: rgb(245, 9, 9);
  padding-left:5px;
}

.product-intro {
  height: 50px!important;
  margin-bottom: 10px!important;
  p {
    height: 50px;
    line-height: 25px;
    padding-left: 10px;
    overflow: hidden;
    white-space: normal;
    text-overflow: ellipsis;
    font-size: 16px;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
  }
}

.el-input__wrapper {
  padding: 0;
}

.des-content {
  width: 100%;
  min-height: 200px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.2);
  border-radius: 5px;
  padding: 30px;

  
  // Markdown样式
  :deep(pre) {
    background-color: #f6f8fa;
    padding: 16px;
    border-radius: 6px;
    overflow-x: auto;
    margin: 10px 0;
    border: 1px solid #e1e4e8;
  }
  
  :deep(code) {
    font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace;
    font-size: 13px;
    tab-size: 4;
  }
  
  :deep(:not(pre) > code) {
    background-color: rgba(175, 184, 193, 0.2);
    padding: 0.2em 0.4em;
    border-radius: 3px;
    font-size: 85%;
  }
  
  :deep(ul), :deep(ol) {
    margin-left: 20px;
    margin-bottom: 10px;
    color: #666;
  }

  :deep(p) {
    margin-bottom: 8px;
    color: #666;
    line-height: 1.6;
  }
  
  :deep(h1), :deep(h2), :deep(h3), :deep(h4), :deep(h5), :deep(h6) {
      margin-top: 5px;
      margin-bottom: 5px;
      color: #333;
    }
    :deep(h1){
      font-size: 1.6em;
      line-height: 1.6em;
    }
    :deep(h2){
      font-size: 1.5em;
      line-height: 1.5em;
    }
    :deep(h3){
      font-size: 1.4em;
      line-height: 1.4em;
    }
    :deep(h4){
      font-size: 1.3em;
      line-height: 1.3em;
    }
    :deep(h5){
      font-size: 1.2em;
      line-height: 1.2em;
    }
    :deep(h6){
      font-size: 1.1em;
      line-height: 1.1em;
    }

  :deep(table) {
    border-collapse: collapse;
    width: 100%;
    margin: 10px 0;
    display: block;
    overflow-x: auto;

    th, td {
      border: 1px solid #ddd;
      padding: 8px;
      text-align: left;
    }

    th {
      background-color: #f2f2f2;
    }
  }
  
  :deep(blockquote) {
    border-left: 4px solid #ddd;
    padding-left: 10px;
    color: #666;
    margin: 10px 0;
  }
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 1s;
}

.fade-enter,
.fade-leave-to {
  opacity: 0;
}


.buy-dialog {
  padding: 10px 15px;
  
  .order-item {
    display: flex;
    align-items: center;
    margin-bottom: 15px;
    padding: 10px;
    border-radius: 8px;
    background-color: #f8f8f8;
    transition: all 0.3s ease;
    
    &:hover {
      background-color: #f0f9eb;
      transform: translateX(5px);
    }
    
    .el-icon {
      font-size: 24px;
      color: #319A19;
      margin-right: 15px;
    }
    
    .order-content {
      flex: 1;
      
      .label {
        color: #909399;
        font-size: 14px;
        margin-right: 8px;
      }
      
      .value {
        font-size: 16px;
        font-weight: 500;
        color: #333;
      }
      
      .price {
        color: #ff6b6b;
        font-weight: bold;
      }
      
      .total-price {
        color: #ff4757;
        font-weight: bold;
        font-size: 18px;
      }
      
      &.remark-section {
        display: flex;
        flex-direction: column;
        
        .label {
          margin-bottom: 8px;
          display: flex;
          align-items: center;
        }
        
        .el-textarea {
          margin-top: 5px;
        }
      }
    }
  }
}

.contact-dialog {
  padding: 10px 15px;
  
  .contact-item {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    padding: 10px;
    border-radius: 8px;
    background-color: #f8f8f8;
    transition: all 0.3s ease;
    
    &:hover {
      background-color: #e8f5e9;
      transform: translateX(5px);
    }
    
    .el-icon {
      font-size: 24px;
      color: #319A19;
      margin-right: 15px;
    }
    
    .contact-content {
      flex: 1;
      
      .label {
        color: #909399;
        font-size: 14px;
        margin-right: 8px;
      }
      
      .value {
        font-size: 16px;
        font-weight: 500;
        color: #333;
      }
    }
  }
}
</style>